package com.lance.answer.question_answer.xj_new;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lance.answer.dto.CourseInfo;
import com.lance.answer.dto.ScoreInfo;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author fengx
 * 新疆一体化答题-考试
 *
 * 拿到每个人的考试成绩：
 *
 * </p>
 */

@Slf4j
public class GetXJAnswerTestingScore {


    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>) d -> {
            assert d != null;
            return d.findElements(By.cssSelector(cssSelector));
        });
    }


    public static void main(String[] args) throws Exception {

        // 检测用户名和密码对不对


        Set<String> names = Sets.newHashSet();
        Set<String> noPwd = Sets.newHashSet();
        for(File f:new File("E:\\XjStudentCourseInfoTmp\\deal").listFiles()){
            String name = f.getName();
            name = name.substring(0,name.length()-5);
            names.add(name);
        }

        InputStream i3 = new FileInputStream("E:\\alluser.txt");
        List<String> allUser2 = IOUtils.readLines(i3, "utf-8");

        for (String user : allUser2) {
            String[] strs = user.split(",");
            String userCode = strs[0];
            if(!names.contains(userCode.toUpperCase())){
                noPwd.add(userCode);
            }
        }
        for(String s:noPwd){
            System.out.println(s);
        }



        // 检测用户名和密码对不对



        int sum = 0;
        for(File d1:new File("E:\\XjScoreInfo").listFiles()){
             for(File file:d1.listFiles()){

                 try {
                     //    System.err.println(file.getAbsolutePath()+"   "+file.length());
                     sum++;
                     List<ScoreInfo> scoreInfoList = JSON.parseArray(IOUtils.toString(new FileInputStream(file),
                             "UTF-8"),ScoreInfo.class);
                     if(scoreInfoList ==null||scoreInfoList.size()<1){
                         continue;
                     }
                     if(scoreInfoList.get(0).getContent().getItems().get(0).getSumScore()<60){
                         String name = file.getName();
                         System.err.println(d1.getName()+"\t  用户名："+name.substring(0,name.length()-10));
                     }
                     else {
                         System.out.println("success:"+d1.getName());
                     }
                 }catch (Exception e){
                   //  e.printStackTrace();
                     System.err.println(file.getName());
                 }
             }
        }
        System.err.println("sum:"+sum);

        Thread.sleep(20000000);


        // 校验是否提交
        int sync = 18 ;


        //预加载所有用户信息
        InputStream inputStream3 = new FileInputStream("E:\\alluser.txt");
        List<String> allUsers = IOUtils.readLines(inputStream3, "utf-8");
        Map<String, String> usernameAndPwd = Maps.newHashMap();

        for (String user : allUsers) {
            String[] strs = user.split(",");
            String userCode = strs[0];
            String pwd = strs[1];
            if (pwd.length() > 12) {
                if (pwd.contains("X")) {
                    pwd = userCode.substring(11, 17);
                } else {
                    pwd = userCode.substring(12);
                }
            }
            usernameAndPwd.put(userCode.toUpperCase(Locale.ROOT), pwd);
        }


        InputStream inputStream = new FileInputStream("E:\\排名map.txt");
        List<String> allKeyValues = IOUtils.readLines(inputStream, "utf-8");
        Map<String, String> mapTmp = Maps.newHashMap();
        for (String keyValues : allKeyValues) {
            String[] strs = keyValues.split("&");
            String k1 = strs[0];
            String v1 = strs[1];
            mapTmp.put(k1, v1);
        }

        //加载所有课程配置
        List<CourseInfo> courseList = Lists.newArrayList();
        for (File file : new File("D:\\新疆一体化测验作业").listFiles()) {
           try {
               if(file.listFiles()[0].length()<1000){
                   continue;
               }
           }catch (Exception e){

           }

            String code = file.getName();
            CourseInfo courseInfo = new CourseInfo();
            courseInfo.setOpenCourseId(Integer.parseInt(code));
            courseInfo.setSubjectName(mapTmp.get(code));
            courseList.add(courseInfo);
            //Constant.COURSE_QUEUE.addLast(new CourseInfo(Integer.parseInt(code), mapTmp.get(code)));
        }
        Collections.sort(courseList);


        // 加载每个课程答案
        for (CourseInfo info : courseList) {
            //获取模板路径,通过流的方式获取文件可以避免被打成jar包之后无法获取文件路径的异常
            String subjectName = info.getSubjectName();
            subjectName = subjectName.trim();
            int  openCourseId = info.getOpenCourseId();
            InputStream inputStream1 = new FileInputStream("D:\\新疆一体化测验作业\\" + openCourseId + "\\" + subjectName + "（测验作业）.json");
            String answerStr = IOUtils.toString(inputStream1, StandardCharsets.UTF_8);
            List<AnswerObject> listAnswerObject = JSONObject.parseArray(answerStr, AnswerObject.class);
            Map<String, AnswerObject> answerMap = Maps.newHashMap();
            for (AnswerObject answerObject : listAnswerObject) {
                answerMap.put(DealJsonString.delHTMLTag(Util.dealContent(answerObject.getQuestionTitle())), answerObject);
            }
            info.setAnswerMap(answerMap);
        }



        // 加载用户答题参数
        LinkedBlockingDeque<CourseInfo> userCourseQueue = new LinkedBlockingDeque<>();
        for (CourseInfo courseInfo : courseList) {
            int  openCourseId = courseInfo.getOpenCourseId();
            // 管理学基础没有考试
            if(openCourseId==30913){
                continue;
            }
            // 职业给
            if(openCourseId==30944||openCourseId ==31126 ||openCourseId == 33355 
                    ||openCourseId == 33544 ||openCourseId == 32013||openCourseId == 31941 ||openCourseId ==32774 ||openCourseId ==32958){
                continue;
            }

            // 31126
            File jsonFile = new File("E:\\XjStudentCourseInfoTmp\\names\\" + courseInfo.getOpenCourseId() + ".json");
            if(!jsonFile.exists()){
                continue;
            }
            InputStream inputStream4 = new FileInputStream(jsonFile);
            String userStr = IOUtils.toString(inputStream4, StandardCharsets.UTF_8);
            // 当前这门课程所有的
            List<String> users = JSONObject.parseArray(userStr, String.class);
            for (String s : users) {
                String pwd = usernameAndPwd.get(s.toUpperCase(Locale.ROOT));
                CourseInfo courseInfo1 = new CourseInfo();
                courseInfo1.setAnswerMap(courseInfo.getAnswerMap());
                courseInfo1.setOpenCourseId(courseInfo.getOpenCourseId());
                courseInfo1.setSubjectName(courseInfo.getSubjectName());
                courseInfo1.setPwd(pwd);
                courseInfo1.setUser(s);
                userCourseQueue.addLast(courseInfo1);
            }
        }


        for (int i = 1; i <= sync; i++) {
            Thread answerThread = new GetXJAnswerTestingScoreTask(null,userCourseQueue);
            //log.info("加载课程ID：{} 名称：{} ", openCourseId,subjectName);
            answerThread.setName( "答题线程--" + i);
            answerThread.start();
        }



    }







}
